package com.infolab.aims.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.infolab.aims.common.AbstractController;
import com.infolab.aims.common.bean.SearchCriteria;
import com.infolab.aims.common.bean.SearchResult;
import com.infolab.aims.common.exception.ResourceNotFoundException;
import com.infolab.aims.domain.Department;
import com.infolab.aims.domain.SystemCodeType;
import com.infolab.aims.domain.SystemCodeValue;
import com.infolab.aims.service.intf.SystemCodeService;


@Controller
@RequestMapping("/systemCode")
@SessionAttributes(value=SystemCodeController.SESSION_SEARCH_CRITERIA)
public class SystemCodeController extends AbstractController {
	
	public static final String SESSION_SEARCH_CRITERIA ="searchCriteria";
	public static final String CONTEXT_PATH ="/systemCode";
	public static final String JSP_MAIN_FORM="systemCodeTypeForm";
	public static final String JSP_FAULT_CODE_FORM="faultCodeForm";
	public static final String JSP_MAIN_SEARCH="systemCodeTypeSearch";
	public static final String JSP_SYSTEM_CODE_VALUE_FORM="systemCodeValueForm";
	public static final String JSP_SYSTEM_CODE_VALUE_FORM_POPUP="systemCodeValueFormPopUp";

	@Autowired
	SystemCodeService systemCodeService;

	@RequestMapping(value="create", method = RequestMethod.GET)
	public String createSystemCodeType(Model model,HttpServletRequest request) {
		SystemCodeType systemCodeType = new SystemCodeType();
		systemCodeType.setActive(true);
		systemCodeType.setAccessDepartment(getCurrentDepartment(request));
		model.addAttribute(systemCodeType);
		return JSP_MAIN_FORM;
	}
	

	@RequestMapping(value="create",method=RequestMethod.POST)
	public String saveSystemCode(@Valid @ModelAttribute SystemCodeType systemCodeType, BindingResult result,Model model,HttpServletRequest request) {

		if (result.hasErrors()) {	
			return JSP_MAIN_FORM;
		}
		systemCodeType.setCreatedBy(getCurrentUserName(request));
		
		systemCodeService.createSystemCodeType(systemCodeType);
		
		setSuccessMessage(getMessageResources("success.create","SystemCodeType " + systemCodeType.getSystemCodeTypeDescription()));
		
		return "redirect:"+CONTEXT_PATH+"/update/" + systemCodeType.getSystemCodeTypeId();
		
	}
	
	@RequestMapping(value="update/{id}",method=RequestMethod.POST)
	public String updateSystemCode(@PathVariable String id,@Valid @ModelAttribute SystemCodeType systemCodeType, BindingResult result,Model model,HttpServletRequest request) {

		if (result.hasErrors()) {	
			return JSP_MAIN_FORM;
		}
		
		systemCodeType.setModifiedBy(getCurrentUserName(request));
		
		systemCodeService.updateSystemCodeType(systemCodeType);
		
		setSuccessMessage(getMessageResources("success.update","SystemCodeType " + systemCodeType.getSystemCodeTypeDescription()));
		
		return "redirect:"+CONTEXT_PATH+"/update/" + systemCodeType.getSystemCodeTypeId();	
		
	}
	
	@RequestMapping(value={"update/{id}","detail/{id}"}, method = RequestMethod.GET)
	public String detailSystemCode(@PathVariable Integer id,Model model,HttpServletRequest request) {
		
		SystemCodeType systemCodeType = systemCodeService.getSystemCodeType(id);
		if(systemCodeType==null) {
			throw new ResourceNotFoundException("SystemCodeType " + id);
		}
		
		model.addAttribute(systemCodeType);
		return JSP_MAIN_FORM;
		
	}
	
	@RequestMapping(value={"updateValue/{id}"}, method = RequestMethod.GET)
	public String detailSystemCodeValue(@PathVariable Integer id,Model model,HttpServletRequest request) {
		
		SystemCodeType SystemCodeType = systemCodeService.getSystemCodeType(id);
		if(SystemCodeType==null) {
			throw new ResourceNotFoundException("SystemCodeType " + id);
		}
		model.addAttribute(SystemCodeType);
		
		String popUp = request.getParameter("popUpFlag")!=null? (String)request.getParameter("popUpFlag"):"";
		if(popUp.equalsIgnoreCase("Y")){
			model.addAttribute("popUpFlag","Y");
			return JSP_SYSTEM_CODE_VALUE_FORM_POPUP;
		}
		return JSP_SYSTEM_CODE_VALUE_FORM;
	
	}
	
	@RequestMapping(value="updateValue/{id}",method=RequestMethod.POST)
	public String updateSystemCodeValue(@PathVariable String id,@ModelAttribute SystemCodeType systemCodeType, BindingResult result,Model model,HttpServletRequest request) {

		
		String popUp = request.getParameter("popUpFlag")!=null? (String)request.getParameter("popUpFlag"):"";
		
		String jspPage = JSP_SYSTEM_CODE_VALUE_FORM;
		if(popUp.equalsIgnoreCase("Y")){ 
			model.addAttribute("popUpFlag","Y");
			jspPage = JSP_SYSTEM_CODE_VALUE_FORM_POPUP;
		}
		
		
		if (validateSystemCodeValue(systemCodeType,result)) {
			systemCodeType.setSystemCodeValues(systemCodeType.getSystemCodeValuesForm());
			model.addAttribute(systemCodeType);
			return jspPage;
		}
		
		systemCodeType.setModifiedBy(getCurrentUserName(request));
		
		systemCodeService.updateSystemCodeValues(systemCodeType);
		
		refreshSystemCode(request, systemCodeType.getSystemCodeTypeCode());
		setSuccessMessage(getMessageResources("success.update","System Code Value"));
		return "redirect:"+CONTEXT_PATH+"/updateValue/" + systemCodeType.getSystemCodeTypeId();	
		
	}

	
	@ModelAttribute(SystemCodeController.SESSION_SEARCH_CRITERIA)
	public SearchCriteria getSystemCodeSearchCriteria()
	{
		return new SearchCriteria();
	}
	

	@RequestMapping(value="search")
	public String searchSystemCode(@ModelAttribute(SystemCodeController.SESSION_SEARCH_CRITERIA) SearchCriteria searchCriteria,@ModelAttribute("currentSearchCriteria") SearchCriteria currentSearchCriteria,Model model,HttpServletRequest request) {
		
		Department accessDepartment = getCurrentDepartment(request);
		if(accessDepartment !=null)
			searchCriteria.addSearchCriteria("accessDepartmentId", accessDepartment.getDepartmentId());
		
		if(currentSearchCriteria.getCurPage()!=null)
			searchCriteria.setCurPage(currentSearchCriteria.getCurPage());
		
		SearchResult searchResult = systemCodeService.searchSystemCodeType(searchCriteria);
		model.addAttribute(searchResult);
		
		return JSP_MAIN_SEARCH;
	}
	
	
	private boolean validateSystemCodeValue(SystemCodeType systemCodeType,BindingResult result)
	{
		List<SystemCodeValue> systemCodeValues = systemCodeType.getSystemCodeValuesForm();
		
		for(int i=0;i<systemCodeValues.size();i++)
		{
			SystemCodeValue systemCodeValue = systemCodeValues.get(i);
			if(StringUtils.isEmpty(systemCodeValue.getSystemCode1()))
				result.reject("error.empty.param", new String[]{"Main code on row "+(i+1)}, "");
		}
		
		
		return result.hasErrors();
	}
}
